package com.xyebank.ledger.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;


public class MD5HashServiceImp implements HashService{
	private static final Logger							logger	= LoggerFactory.getLogger(MD5HashServiceImp.class);

    public String genHash(Object o) {
        String result = "un-except";
        if(o == null) {
        	logger.warn("出现空对象");
            try {
                result = MD5Util.MD5(o.getClass().getName());
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        } else {
            try {
                result = MD5Util.MD5(getSortedString(o));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }
        return result;
    }


    /**
     * 将对象的所有属性排序拼接
     * @param pojo
     * @return
     */
    private static String getSortedString(Object pojo) {
        Map<String, Object> map = beanToMap(pojo);
        if(map == null) return null;

        if(map.containsKey("hash")) {
            map.remove("sign");
        }

        if(map.containsKey("recordDate")) {
            map.remove("recordDate");
        }

        List<String> keys = new ArrayList<String>(map.keySet());
        Collections.sort(keys);

        List<NameValuePair> params = new LinkedList<NameValuePair>();
        for (String k : keys) {
            params.add(new BasicNameValuePair(k, String.valueOf(map.get(k))));
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            if (null != params.get(i).getValue() && !"".equals(params.get(i).getValue())) {
                sb.append(params.get(i).getName());
                sb.append('=');
                sb.append(params.get(i).getValue());
                sb.append('&');
            }
        }
        logger.debug("生成的签名串:{}", sb.toString());

        return sb.toString();
    }


    /**
     * bean 转换为　map
     * @param pojo
     * @return
     */
    public static Map<String, Object> beanToMap(Object pojo) {
        ObjectMapper oMapper = new ObjectMapper();
        Map<String, Object> map = oMapper.convertValue(pojo, Map.class);
        return map;
    }

}
